﻿//地图中的最高点(medium): https://leetcode.cn/problems/map-of-highest-peak/description/
class Solution {
public:
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {
        int m=isWater.size(),n=isWater[0].size();
        vector<vector<int>> ret(m,vector<int>(n,-1));
        queue<pair<int,int>> q;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(isWater[i][j]==1)  
                {
                    ret[i][j]=0;
                    q.push(pair{i,j});
                }
            }
        }
        while(q.size())
        {
            auto [a,b]=q.front();
            q.pop();
            for(int i=0;i<4;i++)
            {
                int x=a+dx[i],y=b+dy[i];
                if(x>=0&&x<m&&y>=0&&y<n&&ret[x][y]==-1)
                {
                    ret[x][y]=ret[a][b]+1;
                    q.push({x,y});
                }
            }      
        }
        return ret;
    }
};

//地图分析(meium): https://leetcode.cn/problems/as-far-from-land-as-possible/description/
class Solution {
public:
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    int maxDistance(vector<vector<int>>& isWater) {
        int m=isWater.size(),n=isWater[0].size();
        vector<vector<int>> ret(m,vector<int>(n,-1));
        queue<pair<int,int>> q;
        int MaxLen=0;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(isWater[i][j]==1)  
                {
                    ret[i][j]=0;
                    q.push(pair{i,j});
                }
            }
        }
        while(q.size())
        {
            auto [a,b]=q.front();
            q.pop();
            for(int i=0;i<4;i++)
            {
                int x=a+dx[i],y=b+dy[i];
                if(x>=0&&x<m&&y>=0&&y<n&&ret[x][y]==-1)
                {
                    ret[x][y]=ret[a][b]+1;
                    q.push({x,y});
                    MaxLen=MaxLen>ret[x][y]?MaxLen:ret[x][y];
                }
            }      
        }
        return MaxLen!=0?MaxLen:-1;
    }
};